package lwk.thread.callable;

import java.util.concurrent.*;

/**
 * @author:lwk
 * @create: 2022-08-13 09:15
 * @Description: Callable线程的启动<br>
 *
 * new Thread().start()开启线程
 * new Thread()的有参构造，目前理解的与Runnable有关
 * 所以要想以该方式启动实现了Callable的线程
 * 就要找到其对应关系
 * Runnable类有一个RunnableFuture的子类接口，该子类接口有个FutureTask(适配类)的实现,该实现类有参数类型为Callable的构造方法
 *
 * 注意FutureTask通过get获取返回值的时候，可能会产生阻塞；结果有缓存
 */
public class CallableTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        // new Thread().start()开启线程
        // new Thread()的有参构造，目前理解的与Runnable有关
        // 所以要想以该方式启动实现了Callable的线程
        // 就要找到其对应关系
        // Runnable类有一个RunnableFuture的子类接口，该子类接口有个FutureTask的实现,该实现类有参数类型为Callable的构造方法

        ThreadCallable thread = new ThreadCallable();

        Runnable runnable = new FutureTask<>(thread);
        new Thread(runnable,"a").start(); // 没有返回值

        RunnableFuture<String> runnableFuture = new FutureTask<>(thread);
        new Thread(runnableFuture,"b").start();
        System.out.println(runnableFuture.get());

        FutureTask<String> futureTask = new FutureTask<>(thread);
        new Thread(futureTask,"c").start();
        new Thread(futureTask,"d").start();
        System.out.println( futureTask.get());

    }
}

class ThreadCallable implements Callable<String>{
    @Override
    public String call() {
        System.out.println(Thread.currentThread().getName());
        return "call";
    }
}